package com.czn.shopdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.shopdemo.mapper.BusinessMapper;
import com.czn.shopdemo.mapper.CategoryMapper;
import com.czn.shopdemo.mapper.UserMapper;
import com.czn.shopdemo.model.Business;
import com.czn.shopdemo.model.Category;
import com.czn.shopdemo.model.Goods;
import com.czn.shopdemo.model.User;
import com.czn.shopdemo.model.enums.ResultCodeEnum;
import com.czn.shopdemo.model.exception.CustomException;
import com.czn.shopdemo.service.BusinessService;
import com.czn.shopdemo.utils.JwtUtil;
import com.czn.shopdemo.utils.TokenInfoUtil;
import com.czn.shopdemo.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Zenan Chen
 * @date 2023/4/3 17:52
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Business> getBusinessList() {
        List<Business> businesses = businessMapper.selectList(Wrappers.<Business>query().lambda().eq(Business::getIsDeleted, "0"));
        businesses.stream().forEach(business -> fillBusiness(business));
        return businesses;
    }

    @Override
    public Business getBusinessDetail(String uuid) {
        Business business = businessMapper.selectOne(Wrappers.<Business>query().lambda().eq(Business::getUuid, uuid));
        fillBusiness(business);
        return business;
    }

    @Override
    public void saveBusiness(Business business, HttpServletRequest request) {
        // 新增
        if (Utils.isEmptyStr(business.getUuid())) {
            // 先校验code是否已经存在
            Business businessExist = businessMapper.selectOne(Wrappers.<Business>query().lambda().eq(Business::getCode, business.getCode()));
            if (businessExist != null) {
                throw new CustomException(ResultCodeEnum.CODE_EXIST);
            }
            // 从token获取用户信息，绑定到商户
            Long userId = TokenInfoUtil.getUserId(request);
            business.setUserId(String.valueOf(userId));
            Business dbBusiness = getByUserId(String.valueOf(userId));
            if (null != dbBusiness) {
                throw new CustomException("用户已经有注册的商户了，请不要重复注册！", 211);
            }
            business.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            business.setCreateTime(new Date());
            business.setUpdateTime(new Date());
            businessMapper.insert(business);
            //更新
        } else {
            business.setUpdateTime(new Date());
            // 从token获取用户信息，绑定到商户
            Long userId = TokenInfoUtil.getUserId(request);
            business.setUserId(String.valueOf(userId));
            Business dbBusiness = getByUserId(String.valueOf(userId));
            if (null != dbBusiness) {
                throw new CustomException("用户已经有注册的商户了，请不要重复注册！", 211);
            }
            businessMapper.updateById(business);
        }
    }

    private void fillBusiness(Business business) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getId, business.getUserId());
        User user = userMapper.selectOne(queryWrapper);
        if (null == user) {
            throw new CustomException(ResultCodeEnum.USER_ID_ERROR);
        }
        business.getParam().put("user", user);
    }

    @Override
    public void deleteBusiness(String uuid) {
        LambdaQueryWrapper<Business> wrapper = Wrappers.lambdaQuery(Business.class).eq(Business::getUuid, uuid);
        businessMapper.delete(wrapper);
    }

    public Business getByUserId(String userId) {
        LambdaQueryWrapper<Business> queryWrapper = Wrappers.lambdaQuery(Business.class).eq(Business::getUserId, userId);
        Business business = businessMapper.selectOne(queryWrapper);
        return business;
    }
}
